import { defineStore, acceptHMRUpdate } from "pinia";
import { systemAppStore } from "./system";
import Axios from "axios";
import PsMessageBox from "@/components/message-box";
import { logout } from "@/api/login";
import { getMemberInfo, checkStatus, getUserTsb } from "@/api/user";
import { userRightById, migratePackages } from "@/api/rights";
import {
  getMyCoupons,
  getLimitObtainCoupons,
  multDrawCoupon
} from "@/api/coupon";
import { passVersion } from "@/utils";
import { kefuUrl } from "@/utils/costum";
import { getRightIdByType } from "@/utils/userRights";
import type { RIGHT_IDS } from "@/utils/userRights";
import { invokeAPi, invokeAsyncAPi } from "@/xz-fn";
import { openLink } from "@/utils/costum-api";
interface RIGHTS_LEFT {
  WORD?: any;
  SCREENSHOT?: any;
  DICT?: any;
  ONLINE?: any;
  PDF?: any;
  PLAY?: any;
}
export const userAppStore = defineStore({
  id: "user",
  state: () => ({
    token: "",
    lenovoToken: '', //联想token
    hasLogin: false,
    userInfo: {} as any,
    anonymousId: "",
    userTsbCount: 0, // 用户翻译币
    rightsLeft: {} as RIGHTS_LEFT,
    ACDialogType: "", // 账号对话框操作类型
    ACDialogQuery: {},
    confirm: false,
    couponExpiresSoon: false, // 是否提醒用户券快过去了
    canReceiveMaxDiscount: 0, // 用户可领优惠券的最高金额, 单位分
    couponNumber: 0, // 用户券数量
    payConfig: {}
  }),
  actions: {
    getToken() {
      return invokeAsyncAPi("fq_GetLoginToken")
        .then((token) => {
          this.token = token as unknown as string;
        });
    },
    setToken(token: string) {
      this.token = token;
    },
    setPayConfig(config: any) {
      this.payConfig = config
    },
    setLxToken(token: string) {
      this.lenovoToken = token;
    },
    getLxToken() {
      return new Promise((resolve, reject) => {
        invokeAsyncAPi('xz_lyget_token').then(res => {
          console.log('xz_lyget_token：', res)
          if (res) {
            this.setLxToken(res)
            resolve(void 0)
          } else {
            reject(res)
          }
        }).catch(e => {
          reject(e)
        })
      })
    },
    getPayConfig() {
      return new Promise((resolve, reject) => {
        invokeAsyncAPi('xz_lygetpayconfig').then(res => {
          console.log('xz_lygetpayconfig: ', res)
          if (res) {
            this.setPayConfig(res)
            resolve(void 0)
          } else {
            reject(res)
          }
        }).catch(e => {
          reject(e)
        })
      })
    },
    setLoginState(val: boolean) {
      this.hasLogin = val;
    },
    checkStatus() {
      return new Promise<void>((resolve, reject) => {
        checkStatus()
          .then(() => {
            this.hasLogin = true;
            resolve();
          })
          .catch((e: any) => {
            this.hasLogin = false;
            reject(e);
          });
      });
    },
    /**
     * 获取用户基础信息
     * @param {boolean} runSourceData 是否返回会员信息源数据
     * @param {boolean} isMigratePkg 是否操作迁移权益包
     */
    getUserInfo(runSourceData: boolean = false, isMigratePkg: boolean = false, noSet: boolean = false ) {
      return new Promise((resolve, reject) => {
        Axios.all([
          getMemberInfo()
        ])
          .then(
            Axios.spread(async (res1) => {
              if(isMigratePkg && passVersion(systemAppStore().appInfo.version, '1.0.0.6')){
                const newRes1 = await this.migrateRightPackages(res1?.data?.buy_right_package).catch(() => null)
                if (newRes1) {
                  // 存在 newRes1 说明权益包迁移成功
                  invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
                    "action": "member-change",
                    "data": { type: "migrate-right-success", info: newRes1.data }
                  }))
                  invokeAPi('fq_update_member_info', JSON.stringify(newRes1));

                  res1 = newRes1
                }
              }

              let sourceData
              const data = res1.data || {};
              
              if(runSourceData){
                sourceData = JSON.parse(JSON.stringify(res1))
              } 
              
              !noSet && this.setUserInfo(data);
              resolve(sourceData || data);
            })
          )
          .catch((e) => {
            reject(e);
          });
      });
    },
    resetUserInfo(isCallXZ = true) {
      this.hasLogin = false;
      this.token = "";
      this.userInfo = {};
      this.userTsbCount = 0;
      if (isCallXZ) {
        invokeAPi("xz_exit");
      }
      PsMessageBox.close();
    },
    /**
     * 合并用户基础信息
     */
    mergeUserInfo(data = {}) {
      this.userInfo = Object.assign({}, this.userInfo, data);
      invokeAPi(
        "xz_update_user_info",
        JSON.stringify({
          username: this.userInfo.Nickname,
          headimgurl: this.userInfo.Portrait
        })
      );
    },
    /**
     * 设置用户信息
     */
    setUserInfo(data: any = {}) {
      // const allPackages = systemAppStore().appInfo.allPackages
      const allPackages = [import.meta.env.VITE_APP_PKGID_OLD, import.meta.env.VITE_APP_PKGID] // 兼容旧版本

      data.buy_right_package = (data.buy_right_package || []).filter(
        (item: { pkg_id: string }) => {
          return allPackages.some(
            (pkg_id: string) => item.pkg_id === pkg_id
          );
        }
      );
      data.is_member = data.buy_right_package.some(
        (item: {
          unlimited: boolean;
          expire_at: string | number | Date;
        }) =>
          item.unlimited ||
          new Date(item.expire_at).getTime() / 1000 > data.server_time
      );
      data.has_buy = data.buy_right_package.some(
        (it: { has_buy: boolean }) => it.has_buy
      );
      console.log('userInfo：', data)
      this.userInfo = data;
    },
    /**
     * 检查并迁移权益包
     */
    async migrateRightPackages(list: any[] = []) {
      const isHasOldPackages = (list || []).some(
        (item: { pkg_id: string }) => {
          return import.meta.env.VITE_APP_PKGID_OLD === item.pkg_id;
        }
      );
      if(!isHasOldPackages) return

      const res: any = await migratePackages({
        pkg_id: import.meta.env.VITE_APP_PKGID_OLD
      }).catch(() => {})

      if(res?.data?.sub_code === 'ok'){
        return this.getUserInfo(true, false, true)
      }
    },
    /**
     * 以默认方式打开登录
     */
    login(obj?: any) {
      obj = obj || {}
      
      if (typeof obj === "string") {
        obj = {
          type: obj
        };
      }
      if (!obj.type) {
        obj.type = localStorage.getItem("loginType") || ""
      }
      if(!import.meta.env.VITE_APP_LOGINWAY.split(",").includes(obj.type)){
        obj.type = import.meta.env.VITE_APP_LOGINWAY.split(",")[0];
      }
      this.setACDialogType(obj);
    },
    /**
     * 打开登录窗口
     */
    openLogin() {
      invokeAPi("fq_ShowLogin");
    },
    /**
     * 退出登录
     */
    logout() {
      return logout({ uuid: systemAppStore().appInfo.uuid }).then(() => {
        this.resetUserInfo();
      });
    },
    setCustomerConfirm(message: string) {
      if (!this.confirm) {
        this.confirm = true;
        setTimeout(() => {
          PsMessageBox({
            dangerouslyUseHTMLString: true,
            message: message,
            confirmButtonText: "联系客服",
            // iconClass: "error",
            center: true,
            beforeClose: (action: string, _instance: any, done: any) => {
              if (action === "confirm") {
                openLink(kefuUrl);
              } else {
                this.confirm = false;
                done();
              }
            }
          });
        }, 50);
      }
    },
    setLogoutConfirm(message: string) {
      if (!this.confirm) {
        this.confirm = true;
        setTimeout(() => {
          PsMessageBox({
            message,
            iconClass: "error"
          })
            .then(() => {
              this.openLogin();
            })
            .finally(() => {
              this.confirm = false;
            });
        }, 50);
      }
    },
    setAnonymousId(id: string) {
      this.anonymousId = id;
    },
    async getRightsLeft(
      translateType: keyof RIGHT_IDS,
      { isCache = true } = {}
    ) {
      if (isCache && this.rightsLeft[translateType]) {
        return this.rightsLeft[translateType];
      }
      const right_id = getRightIdByType(translateType);
      return userRightById({
        right_id
      }).then((res: { data: any }) => {
        this.rightsLeft[translateType] = res.data;
        return res;
      });
    },
    /**
     * 获取用户翻译币
     */
    async getTsbCount() {
      if (!this.hasLogin) {
        this.userTsbCount = 0;
        return 0;
      }
      return new Promise((resolve, reject) => {
        getUserTsb({
          unit_id: "tsb"
        })
          .then((res: any) => {
            const { count } = res?.data || {};
            this.userTsbCount = count || 0;
            resolve(this.userTsbCount);
          })
          .catch(reject);
      });
    },
    /**
     * 消费
     * @param {String} funType 功能权益类型
     * @param {String} engine 引擎
     */
    async rightConsume(rightType: keyof RIGHT_IDS, engine: string) {
      if (engine) {
        if (this.hasLogin) {
          await this.getTsbCount();
        }
        return;
      }
      await this.getRightsLeft(rightType, { isCache: false });
    },
    setTsbCount(val: number) {
      this.userTsbCount = val || 0;
    },
    /**
     * 控制账号弹框操作类型
     * @param {string,Object} data - 类型
     * * forgetPwd 打开找回密码
     * * 为空，则关闭
     */
    setACDialogType(data: string | any) {
      let type;
      let query;
      if (typeof data === "string") {
        type = data;
      } else {
        type = data.type;
        query = data.query;
      }
      this.ACDialogType = type;
      this.ACDialogQuery = query || {};
    },

    /**
     * 获取我的优惠券
     */
    getMyCoupons(isNow = true) {
      return new Promise((resolve) => {
        getMyCoupons({
          last_id: 0,
          bus_type: isNow ? "" : "expire",
          show_pos: "draw_center",
          sort: "amount_desc",
          hide_has_draw: false,
          max_size: 200,
          filter_appid: systemAppStore().appInfo.appID
        })
          .then(({ data, res_headers }: any) => {
            let { date: serverTime } = res_headers || {};
            const localTime = Math.round(Date.now() / 1000);
            serverTime = serverTime
              ? Math.round(new Date(serverTime).getTime() / 1000)
              : localTime;
            const couponList = data.list && data.list.length ? data.list : [];
            if (isNow) {
              couponList.forEach((it: any) => {
                it.serverTime = serverTime;
                it.localTime = localTime;
              });
              this.couponNumber = couponList.length;
              this.couponExpiresSoon = couponList.some((it: any) => {
                return it.expire_at < Math.round(serverTime + 24 * 60 * 60);
              });
            }
            resolve(couponList);
          })
          .catch(() => resolve([]));
      });
    },
    /**
     * 自动领取优惠券
     */
    async autoMutiDrawCoupon() {
      let couponList: any[] = []
      try {
        const res: any = await getLimitObtainCoupons({
          pkg_id: systemAppStore().appInfo.allPackages.length && systemAppStore().appInfo.allPackages[0],
          show_pos: 'draw_center',
          sort: 'amount_desc',
          hide_has_draw: true,
          max_size: 200,
          draw_method: 'auto'
        })
        const { code, data } = res
        if (code === 200) {
          couponList = data.list && data.list.length ? data.list : []
        } else {
          couponList = []
        }
      } catch (e) {
        return Promise.reject()
      }

      if (!couponList.length) {
        return Promise.reject()
      }
      return new Promise((resolve) => {
        const _resolve = resolve
        async function _draw(coupon_ids:number[], limit = 5) {
          const requestIds = coupon_ids.splice(0, limit)
          try {
            await multDrawCoupon({
              coupon_id: requestIds
            })
          } finally {
            if (coupon_ids.length) {
              _draw(coupon_ids)
            } else {
              _resolve({})
            }
          }
        }
        const couponIds = couponList.map((coupon) => coupon.id)
        _draw(couponIds, 5)
      })
    },
    /** 获取用户可领优惠券的最高金额 */
    getCanReceiveMaxDiscount() {
      if (!this.hasLogin) {
        return this.setCanReceiveMaxDiscount(0);
      }
      getLimitObtainCoupons({
        pkg_id: systemAppStore().appInfo.allPackages[0],
        show_pos: "draw_center",
        sort: "amount_desc",
        hide_has_draw: true,
        max_size: 200,
        draw_method: "hand"
      }).then(({ data }) => {
        const nums = data?.list?.map(({ amount }: { amount: number }) => amount);
        this.setCanReceiveMaxDiscount(Math.max(...nums, 0));
      });
    },
    setCanReceiveMaxDiscount(val = 0) {
      this.canReceiveMaxDiscount = val;
    }
  }
});
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(userAppStore, import.meta.hot));
}
